<template>
  <div class="order-create-page">
    <!-- 页面标题 -->
    <van-nav-bar title="自助下单" left-text="返回" left-arrow @click-left="$router.go(-1)" />

    <div class="page-content">
      <!-- 抽样单扫码区域 -->
      <section class="scan-section">
        <div class="section-header">
          <van-icon name="qr" color="#1989fa" size="18" />
          <h3>扫描绑定抽样单</h3>
        </div>
        <div class="scan-container" @click="startScan">
          <div v-if="currentSampleSheet" class="sample-sheet-info">
            <p class="sheet-id">抽样单号: {{ currentSampleSheet.id }}</p>
            <p class="sheet-date">创建时间: {{ formatDate(currentSampleSheet.date) }}</p>
            <p class="sheet-status">状态: 待登记样品</p>
          </div>
          <div v-else class="scan-area">
            <van-icon name="scan" size="60" color="#4e54c8" />
            <p>点击扫描抽样单二维码</p>
          </div>
        </div>
        <van-button v-if="currentSampleSheet" type="primary" size="small" @click="clearSampleSheet">
          更换抽样单
        </van-button>
      </section>

      <!-- 样品登记区域 -->
      <section class="sample-register">
        <div class="section-header">
          <van-icon name="todo-list-o" color="#1989fa" size="18" />
          <h3>样品信息登记</h3>
        </div>

        <van-form ref="sampleForm" class="sample-form">
          <!-- 样品信息表单 -->
          <van-cell-group inset>
            <van-field
              v-model="newSample.sampleName"
              label="样品名称"
              placeholder="请输入样品名称"
              :rules="[{ required: true, message: '请输入样品名称' }]"
            />
            <van-field
              v-model="newSample.sampleType"
              is-link
              readonly
              label="样品类别"
              placeholder="选择样品类别"
              @click="showSampleTypePicker = true"
            />
            <van-popup v-model:show="showSampleTypePicker" position="bottom">
              <van-picker
                :columns="sampleTypes"
                @confirm="onSelectSampleType"
                @cancel="showSampleTypePicker = false"
              />
            </van-popup>

            <van-field
              v-model="newSample.storageCondition"
              is-link
              readonly
              label="储存条件"
              placeholder="选择储存条件"
              @click="showStorageConditionPicker = true"
            />
            <van-popup v-model:show="showStorageConditionPicker" position="bottom">
              <van-picker
                :columns="storageConditions"
                @confirm="onSelectStorageCondition"
                @cancel="showStorageConditionPicker = false"
              />
            </van-popup>

            <van-field
              v-model="newSample.storagePeriod"
              type="number"
              label="储存时长（天）"
              placeholder="输入储存天数"
              :rules="[{ required: true, message: '请输入储存天数' }]"
            >
              <template #extra>
                <span>天</span>
              </template>
            </van-field>

            <van-field
              v-model="newSample.quantity"
              type="number"
              label="样品数量"
              placeholder="输入样品数量"
              :rules="[{ required: true, message: '请输入样品数量' }]"
            >
              <template #extra>
                <van-popover
                  v-model:show="quantityUnitPopover"
                  trigger="click"
                  theme="dark"
                  placement="top"
                >
                  <div class="popover-menu">
                    <div
                      v-for="unit in quantityUnits"
                      :key="unit"
                      @click="newSample.quantityUnit = unit"
                    >
                      {{ unit }}
                    </div>
                  </div>
                  <template #reference>
                    <span class="unit-selector">{{ newSample.quantityUnit }}</span>
                  </template>
                </van-popover>
              </template>
            </van-field>

            <van-field
              v-model="newSample.price"
              type="number"
              label="单价"
              placeholder="输入样品单价"
              :rules="[{ required: true, message: '请输入样品单价' }]"
            >
              <template #extra>
                <span>元/{{ newSample.quantityUnit }}</span>
              </template>
            </van-field>

            <van-field
              v-model="newSample.remarks"
              rows="1"
              autosize
              label="备注"
              type="textarea"
              placeholder="可填写特殊要求"
              class="remarks-field"
            />
          </van-cell-group>

          <div class="form-actions">
            <van-button type="default" class="reset-btn" @click="resetSampleForm">
              重置
            </van-button>
            <van-button
              type="primary"
              class="add-btn"
              @click="addSample"
              :disabled="!currentSampleSheet"
            >
              添加样品
            </van-button>
          </div>
        </van-form>
      </section>

      <!-- 已登记样品列表 -->
      <section class="sample-list-section">
        <div class="section-header">
          <van-icon name="balance-list-o" color="#1989fa" size="18" />
          <h3>已登记样品清单</h3>
          <div class="sample-count">共 {{ samples.length }} 项</div>
        </div>

        <div v-if="samples.length === 0" class="empty-list">
          <van-icon name="orders-o" size="40" color="#c8c9cc" />
          <p>暂无登记样品</p>
          <p>请先添加样品信息</p>
        </div>

        <div v-else class="sample-list-container">
          <van-swipe-cell v-for="sample in samples" :key="sample.id">
            <div class="sample-item">
              <div class="sample-info">
                <h4 class="sample-name">{{ sample.sampleName }}</h4>
                <div class="sample-details">
                  <van-tag type="primary" size="small" class="sample-tag">
                    {{ sample.sampleType }}
                  </van-tag>
                  <span class="quantity"> {{ sample.quantity }}{{ sample.quantityUnit }} </span>
                  <span class="price"> ¥{{ sample.price }}/{{ sample.quantityUnit }} </span>
                  <span class="storage">
                    {{ sample.storagePeriod }}天/{{ sample.storageCondition }}
                  </span>
                </div>
                <p v-if="sample.remarks" class="remarks">
                  <van-icon name="notes" size="14" /> {{ sample.remarks }}
                </p>
              </div>
              <div class="sample-total">¥{{ (sample.quantity * sample.price).toFixed(2) }}</div>
            </div>
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
                @click="removeSample(sample.id)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </section>
    </div>

    <!-- 底部结算区域 -->
    <div class="order-footer">
      <div class="total-section">
        <div class="total-info">
          <div>
            <p class="label">样品数量</p>
            <p class="value">{{ totalQuantity }}件</p>
          </div>
          <div>
            <p class="label">样品总价</p>
            <p class="value price">¥{{ totalPrice.toFixed(2) }}</p>
          </div>
        </div>
        <van-button
          type="primary"
          block
          class="submit-btn"
          @click="confirmOrder"
          :disabled="!currentSampleSheet || samples.length === 0"
        >
          {{ samples.length > 0 ? '提交订单' : '请先添加样品' }}
        </van-button>
      </div>
    </div>

    <!-- 扫码模拟弹出层 -->
    <van-popup v-model:show="showScanDialog" round>
      <div class="scan-dialog">
        <h3>模拟扫描</h3>
        <p class="tip">在实际环境中，这里会调用摄像头进行扫码</p>
        <van-field
          v-model="scanInput"
          placeholder="请输入抽样单号"
          clearable
          center
          class="scan-input"
        >
          <template #button>
            <van-button size="small" type="primary" @click="handleScanInput"> 确认 </van-button>
          </template>
        </van-field>

        <div class="mock-scan-list">
          <div
            class="mock-scan-item"
            v-for="sheet in mockSampleSheets"
            :key="sheet.id"
            @click="mockScan(sheet)"
          >
            <p>抽样单号: {{ sheet.id }}</p>
            <p>创建时间: {{ formatDate(sheet.date) }}</p>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'
import type { SampleType, StorageCondition, QuantityUnit } from '../types/order'
import dayjs from 'dayjs'

// 类型定义
interface SampleSheet {
  id: string
  date: Date
  location: string
  inspector: string
}

interface SampleItem {
  id: string
  sampleName: string
  sampleType: SampleType
  storageCondition: StorageCondition
  storagePeriod: number
  quantity: number
  quantityUnit: QuantityUnit
  price: number
  remarks?: string
}

export default defineComponent({
  name: 'OrderCreatePage',
  setup() {
    const router = useRouter()
    // 当前抽样单信息
    const currentSampleSheet = ref<SampleSheet | null>(null)

    // 显示扫码对话框
    const showScanDialog = ref(false)

    // 模拟扫码输入
    const scanInput = ref('')

    // 样品类型选择器相关状态
    const showSampleTypePicker = ref(false)

    // 储存条件选择器相关状态
    const showStorageConditionPicker = ref(false)

    // 数量单位选择器
    const quantityUnitPopover = ref(false)

    // 样品列表
    const samples = ref<SampleItem[]>([])

    // 新样品表单数据
    const newSample = reactive({
      sampleName: '',
      sampleType: '药品' as SampleType,
      storageCondition: '冷冻（-18℃以下）' as StorageCondition,
      storagePeriod: 30,
      quantity: 1,
      quantityUnit: '盒' as QuantityUnit,
      price: 0,
      remarks: '',
    })

    // 常量定义
    const sampleTypes: SampleType[] = [
      '药品',
      '食品',
      '化学品',
      '生物样本',
      '工业原料',
      '农副产品',
      '其他',
    ]

    const storageConditions: StorageCondition[] = [
      '冷冻（-18℃以下）',
      '冷藏（2-8℃）',
      '常温（10-30℃）',
      '阴凉（<20℃）',
      '深冻（-60℃以下）',
      '恒温（15-25℃）',
    ]

    const quantityUnits: QuantityUnit[] = ['件', '盒', '瓶', '袋', '管', '克', '千克']

    // 模拟抽样单数据
    const mockSampleSheets: SampleSheet[] = [
      {
        id: 'DD20231103001',
        date: new Date(2023, 10, 2, 14, 30),
        location: '上海1号冷冻中心',
        inspector: '张检验员',
      },
      {
        id: 'DD20231102003',
        date: new Date(2023, 10, 1, 10, 15),
        location: '江苏2号冷库',
        inspector: '李检验员',
      },
      {
        id: 'DD20231101007',
        date: new Date(2023, 9, 30, 9, 45),
        location: '浙江温控中心',
        inspector: '王检验员',
      },
    ]

    // 计算总价
    const totalPrice = computed(() => {
      return samples.value.reduce((total, sample) => {
        return total + sample.quantity * sample.price
      }, 0)
    })

    // 计算总数量
    const totalQuantity = computed(() => {
      return samples.value.reduce((total, sample) => {
        return total + sample.quantity
      }, 0)
    })

    // 格式化日期
    const formatDate = (date: Date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    // 扫描抽样单
    const startScan = () => {
      showScanDialog.value = true
      scanInput.value = ''
    }

    // 手动输入扫码
    const handleScanInput = () => {
      if (!scanInput.value) {
        Toast('请输入抽样单号')
        return
      }

      // 查找模拟抽样单
      const matchedSheet = mockSampleSheets.find((sheet) => sheet.id === scanInput.value)

      if (matchedSheet) {
        currentSampleSheet.value = matchedSheet
        showScanDialog.value = false
        Toast('抽样单绑定成功')
      } else {
        Toast('未找到抽样单，请检查单号')
      }
    }

    // 模拟扫码
    const mockScan = (sheet: SampleSheet) => {
      currentSampleSheet.value = sheet
      showScanDialog.value = false
      Toast('抽样单绑定成功')
    }

    // 清除当前抽样单
    const clearSampleSheet = () => {
      Dialog({
        title: '解除绑定',
        message: '确定要解除当前抽样单关联吗？',
      }).then(() => {
        currentSampleSheet.value = null
        samples.value = []
        Toast('已解除绑定')
      })
    }

    // 选择样品类型
    const onSelectSampleType = (value: SampleType) => {
      newSample.sampleType = value
      showSampleTypePicker.value = false
    }

    // 选择储存条件
    const onSelectStorageCondition = (value: StorageCondition) => {
      newSample.storageCondition = value
      showStorageConditionPicker.value = false
    }

    // 重置表单
    const resetSampleForm = () => {
      newSample.sampleName = ''
      newSample.storagePeriod = 30
      newSample.quantity = 1
      newSample.quantityUnit = '盒'
      newSample.price = 0
      newSample.remarks = ''
    }

    // 添加样品
    const addSample = () => {
      // 创建样品对象
      const sample: SampleItem = {
        id: `SM${Date.now()}`,
        sampleName: newSample.sampleName,
        sampleType: newSample.sampleType,
        storageCondition: newSample.storageCondition,
        storagePeriod: newSample.storagePeriod,
        quantity: newSample.quantity,
        quantityUnit: newSample.quantityUnit,
        price: newSample.price,
        remarks: newSample.remarks,
      }

      // 加入样品列表
      samples.value.push(sample)

      // 重置表单
      resetSampleForm()

      Toast('样品添加成功')
    }

    // 移除样品
    const removeSample = (id: string) => {
      samples.value = samples.value.filter((sample) => sample.id !== id)
      Toast('样品已移除')
    }

    // 确认提交订单
    const confirmOrder = () => {
      if (!currentSampleSheet.value) {
        Toast('请先扫描绑定抽样单')
        return
      }

      if (samples.value.length === 0) {
        Toast('请至少添加一个样品')
        return
      }

      Dialog({
        title: '确认订单',
        message: `共计 ${samples.value.length} 个样品，总金额 ${totalPrice.value.toFixed(2)} 元`,
        showCancelButton: true,
      }).then(() => {
        // 模拟提交过程
        Toast.loading({
          duration: 0,
          message: '订单提交中...',
          forbidClick: true,
        })

        // 模拟API请求
        setTimeout(() => {
          Toast.clear()
          Dialog({
            title: '提交成功',
            message: `订单号：OD${Date.now().toString().slice(-8)}`,
            confirmButtonText: '查看订单',
          }).then(() => {
            // 跳转到订单详情页
            console.log('跳转到订单支付')
            router.push('/pays')
          })
        }, 1500)
      })
    }

    return {
      currentSampleSheet,
      showScanDialog,
      scanInput,
      showSampleTypePicker,
      showStorageConditionPicker,
      quantityUnitPopover,
      samples,
      newSample,
      sampleTypes,
      storageConditions,
      quantityUnits,
      mockSampleSheets,
      totalPrice,
      totalQuantity,
      formatDate,
      startScan,
      handleScanInput,
      mockScan,
      clearSampleSheet,
      onSelectSampleType,
      onSelectStorageCondition,
      resetSampleForm,
      addSample,
      removeSample,
      confirmOrder,
    }
  },
})
</script>

<style lang="scss" scoped>
.order-create-page {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .page-content {
    flex: 1;
    overflow-y: auto;
    padding: 0 16px 20px;
    background-color: #f8f9fa;
  }

  .section-header {
    display: flex;
    align-items: center;
    padding: 15px 0;
    font-size: 16px;
    font-weight: bold;

    h3 {
      margin-left: 8px;
      font-size: 16px;
    }
  }

  // 抽样单扫描区域
  .scan-section {
    background: white;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);

    .scan-container {
      height: 120px;
      background-color: #f1f3f5;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s;

      &:active {
        background-color: #e1e5e9;
      }

      .scan-area {
        text-align: center;
        color: #4e54c8;

        p {
          margin-top: 8px;
          font-size: 14px;
        }
      }

      .sample-sheet-info {
        width: 100%;
        padding: 0 20px;

        p {
          margin: 6px 0;
          font-size: 14px;

          &.sheet-id {
            font-weight: bold;
            font-size: 15px;
          }
        }
      }
    }

    .van-button {
      display: block;
      margin: 0 auto;
    }
  }

  // 样品登记表单
  .sample-register {
    background: white;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 15px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);

    .sample-form {
      .form-actions {
        display: flex;
        justify-content: space-between;
        margin-top: 15px;

        .reset-btn,
        .add-btn {
          flex: 1;
        }

        .reset-btn {
          margin-right: 10px;
        }
      }
    }

    .unit-selector {
      padding: 2px 6px;
      background-color: #f1f3f5;
      border-radius: 4px;
      cursor: pointer;

      &:active {
        background-color: #e1e5e9;
      }
    }

    .remarks-field {
      :deep(.van-field__control) {
        min-height: 60px;
      }
    }
  }

  // 样品列表区域
  .sample-list-section {
    background: white;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 80px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .sample-count {
        font-weight: normal;
        color: #969799;
        font-size: 14px;
      }
    }

    .empty-list {
      height: 140px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #c8c9cc;

      p {
        margin: 6px 0;
      }
    }

    .sample-list-container {
      .sample-item {
        display: flex;
        padding: 12px;
        border-bottom: 1px solid #f7f8fa;

        .sample-info {
          flex: 1;
          padding-right: 10px;

          .sample-name {
            margin: 0 0 8px;
            font-size: 15px;
            font-weight: bold;
          }

          .sample-details {
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            font-size: 13px;
            color: #666;
            margin-bottom: 6px;

            span {
              margin-right: 10px;
              line-height: 1.8;
            }

            .sample-tag {
              margin-right: 8px;
            }
          }

          .remarks {
            font-size: 12px;
            color: #888;
            margin: 6px 0 0;
            display: flex;
            align-items: flex-start;

            .van-icon {
              margin-right: 4px;
            }
          }
        }

        .sample-total {
          font-weight: bold;
          color: #ee0a24;
          font-size: 16px;
          min-width: 70px;
          text-align: right;
        }
      }

      .delete-button {
        height: 100%;
      }
    }
  }

  // 底部结算区域
  .order-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    padding: 12px 16px;

    .total-section {
      .total-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 12px;

        .label {
          font-size: 13px;
          color: #969799;
          margin-bottom: 4px;
        }

        .value {
          font-size: 16px;
          font-weight: bold;

          &.price {
            color: #ee0a24;
            font-size: 18px;
          }
        }
      }

      .submit-btn {
        border-radius: 20px;
        font-weight: bold;
      }
    }
  }

  // 扫码对话框
  .scan-dialog {
    padding: 20px;

    h3 {
      margin: 0 0 15px;
      text-align: center;
      font-size: 18px;
    }

    .tip {
      font-size: 13px;
      color: #969799;
      margin-bottom: 20px;
      text-align: center;
    }

    .scan-input {
      background: #f7f8fa;
      border-radius: 8px;
      margin-bottom: 15px;
    }

    .mock-scan-list {
      max-height: 300px;
      overflow-y: auto;

      .mock-scan-item {
        padding: 12px 15px;
        border-bottom: 1px solid #f1f3f5;
        cursor: pointer;

        p {
          margin: 6px 0;
          font-size: 13px;
          color: #333;

          &:first-child {
            font-weight: bold;
          }
        }

        &:active {
          background-color: #f1f3f5;
        }
      }
    }
  }

  // 数量单位弹窗样式
  .popover-menu {
    color: white;
    padding: 8px 0;

    div {
      padding: 8px 20px;

      &:active {
        background-color: rgba(255, 255, 255, 0.1);
      }
    }
  }
}
</style>
